package com.icode.gulimall.auth.controller;

import com.alibaba.fastjson.TypeReference;
import com.icode.common.constant.AuthServerConstant;
import com.icode.common.exception.BizCodeEnum;
import com.icode.common.utils.R;
import com.icode.common.vo.MemberResponseVo;
import com.icode.gulimall.auth.feign.MemberFeignService;
import com.icode.gulimall.auth.feign.ThirdPartyFeignService;
import com.icode.gulimall.auth.vo.MemberLoginVo;
import com.icode.gulimall.auth.vo.UserRegistVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import static com.icode.common.constant.AuthServerConstant.LOGIN_USER;

/**
 * @Author: my_code
 * @Email: my_code@foxmail.com
 * @Create: 2021-01-01 17:51
 */
@Controller
public class LoginController {

    @Autowired
    ThirdPartyFeignService thirdPartyFeignService;

    @Autowired
    MemberFeignService memberFeignService;

    @Autowired
    StringRedisTemplate redisTemplate;

    @PostMapping("/login")
    public String acctLogin(MemberLoginVo loginVo, RedirectAttributes redirectAttributes, HttpSession httpSession) {

        //远程调用获取 压缩密码
        R r = memberFeignService.acctLogin(loginVo);
        if (r.getCode() == 0) {
            MemberResponseVo responseVo = r.getData("data", new TypeReference<MemberResponseVo>() {});
            httpSession.setAttribute(LOGIN_USER, responseVo);
            return "redirect:http://gulimall.com";
        } else {
            Map<String, String> errors = new HashMap<>();
            errors.put("msg", r.getData("msg", new TypeReference<String>() {
            }));
            redirectAttributes.addFlashAttribute("errors", errors);
            return "redirect:http://auth.gulimall.com/login.html";
        }
    }

    @GetMapping("/logout.html")
    public String logout(HttpSession httpSession){

//        httpSession.removeAttribute("")用于清空session中某个特定的属性值
//        httpSession.invalidate()则是清除当前整个session

        httpSession.removeAttribute(LOGIN_USER);
        return "redirect:http://gulimall.com";
    }

    /**
     * redirect：重定向是利用session进行数据的交互，当跳到另一个网页时session将失效
     *
     * @param registVo
     * @param result
     * @param redirectAttributes
     * @return
     */
    @Transactional
    @PostMapping("/register")
    public String regist(@Valid UserRegistVo registVo, BindingResult result,
                         RedirectAttributes redirectAttributes) {

        if (result.hasErrors()) {
            Map<String, String> errors = result.getFieldErrors().stream().collect(Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage));
            //model.addAttribute("errors", errors);
            redirectAttributes.addFlashAttribute("errors", errors);
            //校验出错，转发到注册页
            return "redirect:http://auth.gulimall.com/reg.html";
        }
        //校验验证码
        String code = registVo.getCode();
        boolean checkCode = false; //false -> 验证失败返回校验信息  true -> 验证通过
        String s = redisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + registVo.getPhone());
        if (!StringUtils.isEmpty(s)) {
            String redisCode = s.split("_")[0];
            if (redisCode.equals(code)) {
                //验证通过那就删除验证码，令牌机制
                redisTemplate.delete(AuthServerConstant.SMS_CODE_CACHE_PREFIX + registVo.getPhone());
                checkCode = !checkCode;
            }
        }
        if (checkCode) {
            //真正注册，调用远程服务进行
            R r = memberFeignService.register(registVo);
            if (r.getCode() == 0) {
                System.out.println("注册成功");
                return "redirect:http://auth.gulimall.com/login.html";
            } else {
                System.out.println("注册失败");
                Map<String, String> errors = new HashMap<>();
                errors.put("msg", r.getData("msg", new TypeReference<String>() {
                }));
                redirectAttributes.addFlashAttribute("errors", errors);
                return "redirect:http://auth.gulimall.com/reg.html";
            }
        } else {
            Map<String, String> errors = new HashMap<>();
            errors.put("code", "验证码错误");
            redirectAttributes.addFlashAttribute("errors", errors);
            //校验出错，转发到注册页
            return "redirect:http://auth.gulimall.com/reg.html";
        }
    }

    @ResponseBody
    @RequestMapping("/sms/sendcode")
    public R sendCode(@RequestParam("phone") String phone) {
        //1、接口防刷
        String redisCode = redisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + phone);
        if (!StringUtils.isEmpty(redisCode)) {
            long l = Long.parseLong(redisCode.split("_")[1]);
            if (System.currentTimeMillis() - l < 600000) {
                //60秒内不能再发
                return R.error(BizCodeEnum.SMS_CODE_EXCEPTION.getCode(), BizCodeEnum.SMS_CODE_EXCEPTION.getMsg());
            }
        }


        //2、验证码的再次效验 redis.存key-phone,value-code
        int code = (int) ((Math.random() * 9 + 1) * 1000);
        String codeNum = String.valueOf(code);
        System.out.println(codeNum);
        String redisStorage = codeNum + "_" + System.currentTimeMillis();
        //存入redis，防止同一个手机号在60秒内再次发送验证码
        redisTemplate.opsForValue().set(AuthServerConstant.SMS_CODE_CACHE_PREFIX + phone,
                redisStorage, 60, TimeUnit.SECONDS);

        thirdPartyFeignService.sendCode(phone, codeNum);
        return R.ok();
    }
}
